import html_downloader
import html_outputer
import html_parser
import url_manager


class SpiderMain(object):
    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.output_er = html_outputer.HtmlOutputer()

    def craw(self, root_url):
        self.urls.add_new_url(root_url)
        while self.urls.has_new_url():
            try:

                new_url = self.urls.get_new_url()
                html_content = self.downloader.download(new_url)
                new_urls, new_data = self.parser.parse(new_url, html_content)
                print new_urls
                self.urls.add_new_urls(new_urls)
                print new_data
                self.output_er.collect_data(new_data)
            except Exception as e:
                print e

        self.output_er.output()


if __name__ == '__main__':
    rootUrl = 'http://baike.baidu.com/view/21087.htm'
    objSpider = SpiderMain()
    objSpider.craw(rootUrl)
